package 剑指offer;

public class _54二叉搜索树的第k大节点 {
    int count,k ;
    int res1,res2;
    public int kthLargest(TreeNode root, int k) {
        this.count = k ;
        helper(root);
        return res1;
    }
    public void helper(TreeNode node){
        if(count == 0) return;
        if(node.right != null) {
            helper(node.right);
        }
       if(count >0 ){
           count--;
           if(count ==0 ){
               res1 = node.val;
               return;
           }
       }
        
        if(node.left != null){
            helper(node.left);
        }

    }
/**
 * 以下是优化的代码
 */
    public int kthLargest1(TreeNode root, int k) {
    	this.k = k;
    	dfs(root);
    	return res2;
    }
    public void dfs(TreeNode node) {
    	if(node == null) return;
    	dfs(node.right);
    	if(k == 0) return;
    	if(--k == 0) {
    	res2 = node.val;
    	return;
    	}
    	dfs(node.left);
    }

}